<?php
class M_users extends MY_Model {
	
	private $last_insert_id;
	protected $_table = "users";

	public function verify_user($post)
	{
		
		$date[] = $post['username']['month'];
		$date[] = $post['username']['day'];
		$date[] = $post['username']['year'];
		$lname = $post['lastname'];
		$pass = $post['studentpassword'];

		$dob = DateTime::createFromFormat('m/d/Y',implode('/',$date))->format('Y-m-d');

		$select_profile = 'SELECT firstname,lastname,middlename,e_student_id,e_profile_id,e_id,user_id FROM profiles p
						   LEFT JOIN enrollments e ON e.e_profile_id = p.profile_id
						   WHERE dob = ? AND lastname = ?
						   AND e.registrar_approved = 1
						   AND e.verified = 1
						   ORDER BY e.e_id DESC
						   LIMIT 1';
		$res = $this->db->query($select_profile,[$dob,$lname]);

		// pd($res->result());
		if($res->num_rows() >=1 )
		{
			$row = $res->row();
			// vd($this->verify_password($pass,$row->user_id,'student'));
				
			if($this->verify_password($pass,$row->user_id,'student'))
			{
				
				$userdata = array(
					'userid' => $row->e_profile_id,
					'id_e' => $row->e_id,
					'username' => $row->e_student_id,
					'userType' => 'student',
					'e_f_name' => $row->firstname,
					'e_l_name' => $row->lastname,
					'e_m_name' => $row->middlename,
					'logged_in' => TRUE
				);
				
				$this->session->set_userdata($userdata);
				return true;

			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}
	}
	
	/* 	
		-------------------------------------------------------------------
		hash_password
		12-6-12
		perry
		-------------------------------------------------------------------
		hashes the users password
		
		returns the hashed password with salt
	*/
	public function hash_password($password)
	{
		$this->load->helper('passwordcompat');
		return password_hash($password,PASSWORD_BCRYPT);
	}

	/* 	
		-------------------------------------------------------------------
		validate_password
		12-6-12
		perry
		-------------------------------------------------------------------
		validates the users password
		
		returns the hashed password with salt
	*/
	public function validate_password($hashed_password, $password)
	{
		$this->load->helper('passwordcompat');
		return password_verify($password, $hashed_password);
	}
	
	public function change_pass($oldpassword,$newpassword,$id,$type = 'student')
	{

		if($this->verify_password($oldpassword,$id,$type))
		{
			$rawpassword = $newpassword;
			$newpassword = $this->hash_password($newpassword);
			$this->db->set('hashed_password',$newpassword)->where('id',$id)->update('users');
			if($this->db->affected_rows() >= 1)
			{
				$message = (object)array('stat'=>TRUE,'log'=>'Change Password successfull.');
				$this->load->model('M_enrollees');
				$this->M_enrollees->_update_to_username_password_table($id, $rawpassword, $type);
				return $message;
			}else{
				$message = (object)array('stat'=>FALSE,'log'=>'Unable to change password.');
				return $message;
			}
		}else{
			$message = (object)array('stat'=>FALSE,'log'=>'Incorrect Old Password');
			return $message;
		}
	}
	
	/*
	--------------------------------------------------------------------------
	verify_password
	12-6-2012
	tom
	--------------------------------------------------------------------------
	@param id
	@param old password
	checks password from database and matches from user input
	*/	
	public function verify_password($password,$id,$type='student')
	{
		$data = $this->db->select('hashed_password')
						 ->where('id',$id)
						 ->where('userType',$type)
						 ->limit(1)
						 ->get('users');
		// pd($this->db->last_query());
		// vd($data->row());
		if($data->num_rows() >= 1 )
		{
			$h_pass = $data->row()->hashed_password;

			if($this->validate_password($h_pass,$password)){
				return TRUE;	
			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}

	}
	
	public function get_last_insert_id()
	{
		return $this->last_insert_id;
	}

	public function verify_parent($post)
	{
		
		$_user_name = $post['parent_username'];
		$_user_pass = $post['parent_password'];

		$parent_cred = $this->db->where('username',$_user_name)
										->where('userType','user')
										->limit(1)
									   ->get('users');
		
		if($parent_cred->num_rows() >=1 )
		{
			$par = $parent_cred->row();
			if($par->userStatus == 'inactive')
			{
				$stat = ['status'=>false,'log'=>'User login is currently disabled please contact school registrar '];

			}else{
				if($this->verify_password($_user_pass,$par->id,'user'))
				{
					$userdata = array(
						'userid' => $par->id,
						'id_e' => '',
						'username' => $_user_name,
						'userType' => 'guardian',
						'e_f_name' => '',
						'e_l_name' => '',
						'e_m_name' => '',
						'logged_in' => TRUE
					);
					
					$this->session->set_userdata($userdata);
					$stat = ['status'=>true,'log'=>'Login successful'];

				}else{
					$stat = ['status'=>false,'log'=>'Wrong Username password combination.'];
				}
			}
		}else{
			$stat = ['status'=>false,'log'=>'Wrong Username password combination.'];
		}

		return (object)$stat;
	}

	public function change_username($post,$id, $usertype = 'student')
	{	
		if($this->verify_password($post['user_password'],$id,'user')){
			$this->db->set('username',$post['new_username'])->where('id',$id)->limit(1)->update('users');
			if($this->db->affected_rows() >=1 )
			{
				$stat = ['status'=>true,'log'=>'Username Successfully updated, log in to refresh changes.'];
			}else{
				$stat = ['status'=>false,'log'=>'Unable to change parent username.'];	
			}
		}else{
			$stat = ['status'=>false,'log'=>'Wrong Password'];
		}

		return (object)$stat;
	}

	/**
	 * Verify User Email
	 * 
	 * During the forgot password should verify if email is in the database
	 *
	 * @param email string
	 * @param usertype string student/parent
	 * @return object 
	 */
	public function verify_user_email($email = false, $usertype = false)
	{
		$sly = new StdClass;
		$sly->status = false;
		$sly->data = false;

		if($email !== false || $usertype !== false){

			if($usertype === "student"){

				$sql = "
					SELECT 
					u.id,
					p.`email`,
					u.username,
					concat(p.firstname,' ',p.lastname) as fullname
					FROM users u
					LEFT JOIN `profiles` p ON u.id = p.`user_id`
					WHERE u.userType = 'student'
					AND p.`email` = ?;
				";
			}

			if($usertype === "parent"){
				$sql = "
					SELECT 
					id,
					username as email,
					username as username
					FROM users
					WHERE username = ?
					AND userType = 'user'
				";
			}

			$q = $this->db->query($sql, [$email]);

			if($q->num_rows() > 0){

				$sly->status = TRUE;
				$sly->data = $q->result();

				return $sly;
			}
		}

		return $sly;
	}

	/**
	 * username check
	 */
	public function username_check($username = false, $except_id = false)
	{
		if($except_id){
			$this->db->where('id <> ', $except_id);
		}
		
		$this->db->select('username');
		$this->db->where('username', $username);
		$q = $this->db->get('users');
		
		return $q->num_rows() > 0 ? false : true;
	}

	public function register_user($profile_data)
	{
		unset($profile_data['level_id']);
		$profile_data = (object)$profile_data;
		
		//format date and get age from birhtdate
		$d = $this->__format($profile_data->b_month.'/'.$profile_data->b_day.'/'.$profile_data->b_year);
		// pd($d);
		$profile_input['firstname'] = $profile_data->child_fname;
		$profile_input['lastname'] = $profile_data->child_lname;
		$profile_input['middlename'] = strtolower($profile_data->child_mname) == 'none' ? NULL : $profile_data->child_mname;
		$profile_input['nickname'] = $profile_data->child_nickname;
		$profile_input['dob'] = $d->dob;
		$profile_input['age'] = $d->age;
		$profile_input['gender'] = $profile_data->gender;
		$profile_input['pob'] = $profile_data->child_placeofbirth;
		$profile_input['nationality'] = $profile_data->child_nationality;
		$profile_input['religion'] = $profile_data->child_religous;
		$profile_input['present_address'] = $profile_data->child_city_address;
		$profile_input['contact_no'] = $profile_data->child_telno;
		$profile_input['email'] = $profile_data->email;
		$profile_input['how_long_living_present_address'] = $profile_data->child_adresshowlong;
		$profile_input['last_school_name'] = $profile_data->school_last_attended;
		$profile_input['last_school_level'] = $profile_data->school_level_completed;
		$profile_input['last_school_address'] = $profile_data->school_address;
		$profile_input['fathername'] = $profile_data->father_name;
		$profile_input['father_age'] = $profile_data->father_age;
		$profile_input['father_religion'] = $profile_data->father_relaffil;
		$profile_input['father_nationality'] = $profile_data->father_citizenship;
		$profile_input['father_educ_attain'] = $profile_data->father_educ;
		$profile_input['father_hobby_talent'] = $profile_data->father_talent;
		$profile_input['father_occupation'] = $profile_data->father_occup;
		$profile_input['father_office_add'] = $profile_data->father_office_address;
		$profile_input['father_office_num'] = $profile_data->father_office_tel;
		$profile_input['mothername'] = $profile_data->mother_name;
		$profile_input['mother_age'] = $profile_data->mother_age;
		$profile_input['mother_religion'] = $profile_data->mother_relaffil;
		$profile_input['mother_nationality'] = $profile_data->mother_citizenship;
		$profile_input['mother_educ_attain'] = $profile_data->mother_educ;
		$profile_input['mother_hobby_talent'] = $profile_data->mother_talent;
		$profile_input['mother_occupation'] = $profile_data->mother_occup;
		$profile_input['mother_office_add'] = $profile_data->mother_office_address;
		$profile_input['mother_office_num'] = $profile_data->mother_office_tel;
		$profile_input['guardian_name'] = $profile_data->guardian_name;
		$profile_input['relationship'] = $profile_data->guardian_relation;
		$profile_input['guardian_address'] = $profile_data->guardian_address;
		$profile_input['guardian_contact_no'] = $profile_data->guardian_contact_num;
		$profile_input['guardian_reason'] = $profile_data->guardian_reason;
		$profile_input['parent_status'] = $profile_data->parent_status;
		$profile_input['parent_status_how_long'] = $profile_data->status_how_long;
		$profile_input['parent_rights'] = $profile_data->right_over_child;
		$profile_input['parents_rights_who'] = $profile_data->right_over_child_whom;
		$profile_input['child_pos'] = $profile_data->position_of_child;
		$profile_input['child_adopted'] = $profile_data->is_child_adopted;
		$profile_input['child_age_adopted'] = $profile_data->age_of_adoption;
		$profile_input['child_aware_adopted'] = $profile_data->child_aware_adopted;
		$profile_input['mother_present_pregnant'] = $profile_data->mother_presently_pregnant;
		$profile_input['mother_due_date'] = $profile_data->mother_pregnancy_due_date;
		$profile_input['family_deaths'] = $profile_data->family_deaths;
		$profile_input['family_deaths_child_relation'] = $profile_data->family_deaths_relation;
		$profile_input['family_accidents'] = $profile_data->family_accidents;
		$profile_input['family_accidents_child_relation'] = $profile_data->family_accidents_relation;
		$profile_input['what'] = $profile_data->what;
		$profile_input['when'] = $profile_data->when;
		$profile_input['other_household_member1'] = $profile_data->hhmembers1;
		$profile_input['other_household_member2'] = $profile_data->hhmembers2;
		$profile_input['other_household_member3'] = $profile_data->hhmembers3;
		$profile_input['other_household_member4'] = $profile_data->hhmembers4;
		$profile_input['other_household_member5'] = $profile_data->hhmembers5;
		$profile_input['other_household_member6'] = $profile_data->hhmembers6;
		$profile_input['other_household_age1'] = $profile_data->hhmembersage1;
		$profile_input['other_household_age2'] = $profile_data->hhmembersage2;
		$profile_input['other_household_age3'] = $profile_data->hhmembersage3;
		$profile_input['other_household_age4'] = $profile_data->hhmembersage4;
		$profile_input['other_household_age5'] = $profile_data->hhmembersage5;
		$profile_input['other_household_age6'] = $profile_data->hhmembersage6;
		$profile_input['languages_spoken_at_home'] = $profile_data->language_at_home;
		$profile_input['family_activities'] = $profile_data->family_activities;
		$profile_input['family_activities_frequent'] = $profile_data->family_activities_frequent;
		$profile_input['time_spent_on_tv'] = $profile_data->tv_time;
		$profile_input['tv_whom'] = $profile_data->tv_whom;
		$profile_input['time_spent_on_radio'] = $profile_data->radio_time;
		$profile_input['radio_whom'] = $profile_data->radio_whom;
		$profile_input['time_spent_on_pc'] = $profile_data->computergames_time;
		$profile_input['pc_whom'] = $profile_data->computergames_whom;
		$profile_input['child_responsibilty'] = $profile_data->child_responsibilities;
		$profile_input['responsibility_what'] = $profile_data->child_responsibilities_what;
		$profile_input['child_playgroup'] = $profile_data->child_play_group;
		$profile_input['child_playgroup_frequent'] = $profile_data->child_play_group_frequent;
		$profile_input['child_interest'] = $profile_data->other_interest;
		// $profile_input['sibling_fname1'] = $profile_data->siblingfname1;
		// $profile_input['sibling_lname1'] = $profile_data->siblinglname1;
		// $profile_input['sibling_age1'] = $profile_data->siblingage1;
		// $profile_input['sibling_fname2'] = $profile_data->siblingfname2;
		// $profile_input['sibling_lname2'] = $profile_data->siblinglname2;
		// $profile_input['sibling_age2'] = $profile_data->siblingage2;
		// $profile_input['sibling_fname3'] = $profile_data->siblingfname3;
		// $profile_input['sibling_lname3'] = $profile_data->siblinglname3;
		// $profile_input['sibling_age3'] = $profile_data->siblingage3;
		// $profile_input['sibling_fname4'] = $profile_data->siblingfname4;
		// $profile_input['sibling_lname4'] = $profile_data->siblinglname4;
		// $profile_input['sibling_age4'] = $profile_data->siblingage4;
		// $profile_input['sibling_fname5'] = $profile_data->siblingfname5;
		// $profile_input['sibling_lname5'] = $profile_data->siblinglname5;
		// $profile_input['sibling_age5'] = $profile_data->siblingage5;
		// $profile_input['sibling_fname6'] = $profile_data->siblingfname6;
		// $profile_input['sibling_lname6'] = $profile_data->siblinglname6;
		
		//Additional data if enrollee is primary or preschool
		$profile_input['preschool_age_first_walked'] = isset($profile_data->age_first_walked) ? $profile_data->age_first_walked: NULL;
		$profile_input['preschool_age_first_talked'] = isset($profile_data->age_first_talked) ? $profile_data->age_first_talked: NULL;
		$profile_input['preschool_w_for_urinate'] = isset($profile_data->w_for_urinate) ? $profile_data->w_for_urinate: NULL;
		$profile_input['preschool_w_for_bowel'] = isset($profile_data->w_for_bowel) ? $profile_data->w_for_bowel: NULL;
		$profile_input['preschool_w_usual_time'] = isset($profile_data->w_usual_time) ? $profile_data->w_usual_time: NULL;
		$profile_input['preschool_child_dress'] = isset($profile_data->child_dress) ? $profile_data->child_dress: NULL;
		$profile_input['preschool_child_undress'] = isset($profile_data->child_undress) ? $profile_data->child_undress: NULL;
		$profile_input['preschool_hand_orientation'] = isset($profile_data->hand_orientation) ? $profile_data->hand_orientation: NULL;
		$profile_input['preschool_self_feed'] = isset($profile_data->self_feed) ? $profile_data->self_feed: NULL;
		$profile_input['preschool_stayinplace'] = isset($profile_data->stayinplace) ? $profile_data->stayinplace: NULL;
		$profile_input['preschool_joinothereating'] = isset($profile_data->joinothereating)? $profile_data->joinothereating: NULL;
		$profile_input['preschool_food_preferences'] = isset($profile_data->food_preferences)? $profile_data->food_preferences: NULL;
		$profile_input['preschool_drink_from_bottle'] = isset($profile_data->drink_from_bottle)? $profile_data->drink_from_bottle: NULL;
		$profile_input['preschool_toilet_trained'] = isset($profile_data->toilet_trained)? $profile_data->toilet_trained: NULL;
		$profile_input['preschool_pasttime_watch'] = isset($profile_data->pt_watch)? $profile_data->pt_watch: NULL;
		$profile_input['preschool_pasttime_boardgames'] = isset($profile_data->pt_boardgames)? $profile_data->pt_boardgames: NULL;
		$profile_input['preschool_pasttime_comp'] = isset($profile_data->pt_comp)? $profile_data->pt_comp: NULL;
		$profile_input['preschool_pasttime_reading'] = isset($profile_data->pt_reading)? $profile_data->pt_reading: NULL;
		$profile_input['preschool_pasttime_sports'] = isset($profile_data->pt_sports)? $profile_data->pt_sports: NULL;
		$profile_input['preschool_milkbottle'] = isset($profile_data->pe_dmilk)? $profile_data->pe_dmilk: NULL;
		$profile_input['preschool_studytime'] = isset($profile_data->pe_study)? $profile_data->pe_study: NULL;
		
		//Additional data if enrollee is secondary or gradeschool
		$profile_input['secondary_study_time'] = isset($profile_data->sec_study_time) ? $profile_data->sec_study_time : NULL;
		$profile_input['secondary_study_whom'] = isset($profile_data->sec_study_whom) ? $profile_data->sec_study_whom : NULL;
		$profile_input['secondary_child_pastime'] = isset($profile_data->sec_child_pastime) ? $profile_data->sec_child_pastime : NULL;
		$profile_input['secondary_child_htd'] = isset($profile_data->sec_child_htd) ? $profile_data->sec_child_htd : NULL;
		$profile_input['secondary_child_music'] = isset($profile_data->sec_child_music) ? $profile_data->sec_child_music : NULL;
		$profile_input['secondary_child_hfrus'] = isset($profile_data->sec_child_hfrus) ? $profile_data->sec_child_hfrus : NULL;
		$profile_input['secondary_child_curfew'] = isset($profile_data->sec_child_curfew) ? $profile_data->sec_child_curfew : NULL;
		$profile_input['secondary_talkingl'] = isset($profile_data->sec_talkingl) ? $profile_data->sec_talkingl : NULL;
		$profile_input['secondary_answering'] = isset($profile_data->sec_answering) ? $profile_data->sec_answering : NULL;
		$profile_input['secondary_slamdoor'] = isset($profile_data->sec_slamdoor) ? $profile_data->sec_slamdoor : NULL;
		$profile_input['secondary_misbehave_others'] = isset($profile_data->sec_misbehave_others) ? $profile_data->sec_misbehave_others : NULL;
		$profile_input['secondary_rhle'] = isset($profile_data->sec_rhle) ? $profile_data->sec_rhle : NULL;
		$profile_input['go_home_independently'] = isset($profile_data->al_tghome) ? $profile_data->al_tghome : NULL;
		
		//Additional data if enrollee is intermediate or highschool
		$profile_input['intermediate_watch'] = isset($profile_data->hs_watch) ? $profile_data->hs_watch : NULL;
		$profile_input['intermediate_boardgames'] = isset($profile_data->hs_boardgames) ? $profile_data->hs_boardgames : NULL;
		$profile_input['intermediate_comp'] = isset($profile_data->hs_comp) ? $profile_data->hs_comp : NULL;
		$profile_input['intermediate_reading'] = isset($profile_data->hs_reading) ? $profile_data->hs_reading : NULL;
		$profile_input['intermediate_other_pt'] = isset($profile_data->hs_other_pt) ? $profile_data->hs_other_pt : NULL;
		$profile_input['intermediate_spend_study'] = isset($profile_data->hs_spend_study) ? $profile_data->hs_spend_study : NULL;
		$profile_input['intermediate_first_mens'] = isset($profile_data->hs_first_mens) ? $profile_data->hs_first_mens : NULL;
		$profile_input['intermediate_signal_mens'] = isset($profile_data->hs_signal_mens) ? $profile_data->hs_signal_mens : NULL;
		
		//additional fields for foreign students
		$profile_input['name_ext'] = $profile_data->child_name_ext;
		$profile_input['f_ssp_status'] = $profile_data->nationality_ssp_number;
		$profile_input['f_visa_status'] = $profile_data->nationality_visa_status;
		$profile_input['f_authorized_stay'] = $profile_data->nationality_auth_stay;
		$profile_input['f_passport_no'] = $profile_data->nationality_passport_no;
		$profile_input['f_i_card_no'] = $profile_data->nationality_icard_no;
		$profile_input['f_date_if_issue'] = $profile_data->nationality_date_issued;
		$profile_input['created'] = NOW;
		
		
		//counter for enrollment
		$profile_input['enrollment_resume_key'] = strtolower($this->hs->encrypt(intval(time())+intval(mt_rand(1,99))));
		$profile_input['enrollment_step'] = 'registration form, Personal information';

		// pd($profile_input);
		$this->db->insert('profiles',$profile_input);
		$this->last_insert_id = $this->db->insert_id();
		// $this->_process_siblings($profile_data->sibling,$this->last_insert_id);
		
		if($this->session->set_userdata('forenrollagain') == FALSE)
		{
			$this->session->set_userdata('forenrollagain',$this->last_insert_id);
		}
		
		return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
	}

	private function __format($date)
	{
		$date = DateTime::createFromFormat('m/d/Y', $date);
		if($date)
		{
			$dob = $date->format('Y-m-d');
			$birthday = strtotime($dob);
			$time = time();
			$seconds = $time - $birthday;
			$age = floor($seconds / 31536000);
			return (object)array('dob'=>$dob,'age'=>$age);
		}
	}
}
?>